package com.ctg.behavior.calc.impala.transfer.property;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.CtSQLTransfer;
import com.ctg.behavior.calc.utils.CtCalcPropertyUtils;
import com.ctg.behavior.common.calc.CtCalc;
import com.ctg.behavior.common.calc.CtCalcPropertyType;
import com.ctg.behavior.common.consts.CtFieldConsts;
import com.ctg.behavior.common.consts.CtPropertyConsts;
import com.ctg.behavior.common.properties.CtPropertyValuesCalcBody;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtPropertyValuesTransfer implements CtSQLTransfer {

	@Override
	public String doTransfer(CtCalc calcObject, CtSQLParam sqlParam) {
		if (!(calcObject instanceof CtPropertyValuesCalcBody)) {
			log.warn("calcObject is not CtPropertyValuesCalcBody, class={}", calcObject.getClass());
			return "";
		}
		CtPropertyValuesCalcBody calcBody = (CtPropertyValuesCalcBody) calcObject;
		log.info("PropertyValuesCalcBody={}", JSON.toJSONString(calcBody));

		String field = calcBody.getField();
		String fuzzyStr = calcBody.getFuzzyStr();
		Integer limit = calcBody.getLimit();
		String appId = calcBody.getAppId();
		CtCalcPropertyType calcPropertyType = CtCalcPropertyUtils.getValueType(field);
		if (calcPropertyType.getType().isEmpty()) {
			log.error("calcPropertyType={}", calcPropertyType);
			return null;
		}

		// 组装SQL
		StringBuilder impalaSQL = new StringBuilder();
		impalaSQL.append(" SELECT  ").append(calcPropertyType.getProperty()).append(" AS pname ");
		impalaSQL.append(" , count(*) AS total ");

		if (CtPropertyConsts.PROPERTY_EVENT.equalsIgnoreCase(calcPropertyType.getType())) {
			impalaSQL.append(" FROM a_event_parquet_").append(appId);
			impalaSQL.append(" WHERE 1=1 ");
			if (!CtFieldConsts.FIELD_ANYTHING.equals(calcPropertyType.getEvent())) {
				impalaSQL.append(" AND event = '").append(calcPropertyType.getEvent()).append("' ");
			}
		} else if (CtPropertyConsts.PROPERTY_USER.equalsIgnoreCase(calcPropertyType.getType())) {
			impalaSQL.append(" FROM a_user_kudu_").append(appId);
			impalaSQL.append(" WHERE 1=1 ");
		}				
		impalaSQL.append(" AND ").append(calcPropertyType.getProperty()).append(" is not null ");

		if (!StringUtils.isEmpty(fuzzyStr)) {
			impalaSQL.append(" AND ").append(calcPropertyType.getProperty()).append(" LIKE '%").append(fuzzyStr).append("%' ");
		}
		impalaSQL.append(" GROUP BY ").append(calcPropertyType.getProperty());
		impalaSQL.append(" LIMIT ").append(limit).append(" ");

		return impalaSQL.toString();
	}

}
